import { addCommend, getArticleCommend, getArticleDetail, getArticleList } from '@/services';
import {  ICommendItem } from '@/types';
import { Effect, Reducer } from 'umi';

export interface CommendModelState {
  commendList: ICommendItem [];
  commendLength: number;
}

export interface CommendModelType {
  namespace: 'commend';
  state: CommendModelState;
  effects: {
    getArticleCommend: Effect;
    AddArticleCommend: Effect;
  };
  reducers: {
    save: Reducer<CommendModelState>;
  };
}

const CommendModel: CommendModelType = {
  // 数据模型，用来隔离数据防止相互影响
  namespace: 'commend',

  // 数据模型状态，相当于vuex的state
  state: {
    commendList: [],
    commendLength: 0,   
  },

  // 异步操作，相当于vuex的action
  effects: {
    // 先简单记忆，*相当于async，yield相当于await
    *getArticleCommend({payload}, {call, put}){

      let result = yield call(getArticleCommend, payload.id,payload.page);     
     
      if (result.data){
        yield put({
          type: 'save',
          payload: {
            commendList: result.data[0],
            commendLength: result.data[1]
          }
        })
      }
    },
    // 提交评论
    *AddArticleCommend({payload}, {call, put}){
      let result = yield call(addCommend, payload);     
    },
    
  },

  // 同步操作，相当于vuex的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },

  }
};

export default CommendModel;
